<template>
  <div class="rightBodyContent">
    <div class="rightBodyContent-in">
    <div class="hearder-search">
      <div class="breadcrumb-container button-line">
        <el-button type="primary" @click.native="addBook" size="small">添加设备</el-button>
        <el-button @click="deleteAll('delete')" size="small" :disabled="handleSelection.length!==0?false:'disabled'">批量删除</el-button>
      </div>
    </div>
    <!--本体列表，数据 -->
    <div class="table-body">
      <div class="table-body-box">
        <el-table
                ref="multipleTable"
                :data="arryList"
                :stripe="tableStripe"
                :border="tableBorder"
                tooltip-effect="dark"
                style="width: 100%"
                header-cell-class-name="table-text-c"
                cell-class-name="table-text-c"
                @selection-change="handleSelectionChange">
          <el-table-column
                  type="selection"
                  width="50">
          </el-table-column>
          <el-table-column
                  prop="id"
                  label="序号"
                  width="50">
          </el-table-column>
          <el-table-column
                  prop="created"
                  label="添加时间">
          </el-table-column>
          <el-table-column
                  prop="device_name"
                  label="设备名称">
          </el-table-column>
          <el-table-column
                  prop="position"
                  label="设备位置">
          </el-table-column>
          <el-table-column
                  prop="num"
                  label="数量"
                  width="70">
          </el-table-column>
          <el-table-column
                  prop="status"
                  label="设备状态"
                  width="80">
            <template slot-scope="scope"><span :class="scope.row.status==1?'canborrow':'notborrow'">{{scope.row.status==1?'正常':'报修'}}</span></template>
          </el-table-column>
          <el-table-column
                  label="操作"
          width="250">
            <template slot-scope="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDetel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!--工具条 分页-->
    <el-col :span="24" class="toolbar">
      <el-pagination
              background
              layout="prev, pager, next"
              :total="pageTotal"
              :page-size="pageSize"
              @current-change="handleSizeChange">
      </el-pagination>
    </el-col>
    <!--编辑界面-->
    <!--<div v-if="editForm">-->
    <el-dialog :title="tieleName" :visible.sync="editFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" :before-close="handleClose">
      <el-form :model="editForm" label-width="130px" :rules="editFormRules" ref="editForm">
        <el-form-item label="设备名称：" prop="name">
          <el-input v-model="editForm.device_name" auto-complete="off" placeholder="填写设备名称"></el-input>
        </el-form-item>
        <el-form-item label="设备位置" @click.native="userInfoFn">
          <el-input v-model="editForm.position" placeholder="选择保修位置" readonly="" type="text"></el-input>
        </el-form-item>
        <el-form-item label="数量：" prop="position">
          <el-input v-model="editForm.num" auto-complete="off" placeholder="填写数量"></el-input>
        </el-form-item>
        <el-form-item label="服务商：" prop="position">
          <el-input v-model="editForm.installer" auto-complete="off" placeholder="填写服务商"></el-input>
        </el-form-item>
        <el-form-item label="服务商电话：" prop="position">
          <el-input v-model="editForm.installer_phone" auto-complete="off" placeholder="填写安装商电话"></el-input>
        </el-form-item>
        <el-form-item label="安装商：" prop="position">
          <el-input v-model="editForm.supplier" auto-complete="off" placeholder="填写安装商"></el-input>
        </el-form-item>
        <el-form-item label="安装商电话：" prop="position">
          <el-input v-model="editForm.supplier_phone" auto-complete="off" placeholder="填写安装商电话"></el-input>
        </el-form-item>
        <!--device_name,num,position,supplier,supplier_phone,installer,installer_phone-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="resetForm">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--</div>-->
    <!--删除咨询框-->
    <el-dialog
            title="提示"
            :visible.sync="dialogVisible"
            width="30%">
      <span>你确定删除这本图书: <span class="bookname">{{bookName}}</span></span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="DetelBook()">确 定</el-button>
      </span>
    </el-dialog>
    <!--选择通知人员-->
    <el-dialog title="选择保修位置" :visible.sync="dialogTableVisible">
      <el-table :data="userList"
                height="300"
                @select-all="selectAll"
                @select="selectFnBox"
                :stripe="tableStripe"
                :border="tableBorder"
                tooltip-effect="dark"
                ref="table">
        <el-table-column
                type="selection"
                width="50">
        </el-table-column>
        <el-table-column label="班级" prop="class_id">
          <template slot-scope="scope">
            {{scope.row.class_id!==''?scope.row.class_id:'数据未添加'}}
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
              :page-size="pageSize"
              layout="prev, pager, next"
              :total="pageuserTotal"
              @current-change="handleSizeChange">
      </el-pagination>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogTableVisible = false">取 消</el-button>
        <el-button type="primary" @click="userlist('yse')">确 定</el-button>
      </div>
    </el-dialog>
    <!--<p class="companySystemline">本系统由厦门易企网络科技有限公司提供技术支持</p>-->
  </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        tableStripe: true, // 是否斑马栏
        tableBorder: true, // 单元格右边边框
        searchWord: '', // 搜索名称
        editLoading: false, // 编辑界面按键缓存
        // <!--device_name,num,position,supplier,supplier_phone,installer,installer_phone-->
        editForm: {
          device_name: '',
          num: '',
          position: '',
          supplier: '',
          supplier_phone: '',
          installer: '',
          installer_phone: ''
        }, // 编辑界面数据
        editFormRules: {
          device_name: [
            {required: true, message: '请填写书名', trigger: 'blur'}
          ],
          num: [
            {required: true, message: '请填写图书存放位置', trigger: 'blur'}
          ],
          supplier: [
            {required: true, message: '请填写库存', trigger: 'blur'}
          ],
          supplier_phone: [
            { required: true, message: '请选择添加时间', trigger: 'change' }
          ],
          installer: [
            { required: true, message: '请选择编辑时间', trigger: 'change' }
          ],
          installer_phone: [
            {required: true, message: '请填写作者', trigger: 'blur'}
          ]
        }, // 表单验证不能为空规则
        addLoading: false,
        editFormVisible: false, // 编辑界面是否显示
        arryList: null, // 数据列表
        pageTotal: 0, // 总页数
        dialogVisible: false, // 删除咨询页
        bookName: '', // 删除书名
        bookEtelId: '', // 删除书名id
        tieleName: '',
        page: 1,
        pageSize: 20,
        handleSelection: [], // checked选中框
        dialogTableVisible: false,
        userList: null,
        pageuserTotal: '',
        applyBookBox: {}, // 选中人员信息
        applyBookBoxInit: {}, // 本页面对应对象
        usersName: ''
      }
    },
    created () {
      // this.InitFn()

    },
    methods: {
      // 初始化
      InitFn () {
        console.log('获取通讯信息')
        this.$fetch('device/index', {p: this.page}).then((response) => {
          console.log('数据：', response)
          if (response.code === 0) {
            this.arryList = response.list.data
            this.pageTotal = response.list.total
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
        let _this = this
        this.$fetch('admin_user/index', {p: this.page}).then((response) => {
          console.log('数据：', response)
          if (response.code === 0) {
            this.userList = response.list.data
            this.pageuserTotal = response.list.total
            let applyBookBoxInit = {}
            for (let i = 0; i < response.list.data.length; i++) {
              applyBookBoxInit[response.list.data[i].id] = response.list.data[i]
            }
            this.applyBookBoxInit = applyBookBoxInit
            _this.$nextTick(function () {
              _this.checked() // 每次更新了数据，触发这个函数即可。
            })
          } else {
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 分页
      handleSizeChange (val) {
        this.page = val
        console.log(val)
        this.InitFn()
      },
      handleSelectionChange (val) {
        console.log(val) // 所有选中值
        this.handleSelection = val
      },
      // 批量删除 禁用 恢复
      deleteAll (option) {
        console.log('批量删除数据')
        let id_ = []
        this.handleSelection.forEach((item, index) => {
          id_.push(item.id)
        })
        console.log('提交的id', id_.join(','))
        // book/forbid/id/ 禁用
        // book/resume/id/ 恢复
        // delete book/delete 删除
        let url_ = '' // 恢复
        let message = ''
        let _self = this
        if (option === 'forbid') {
          url_ = 'book/forbid' // 禁用
          message = '禁用成功'
        } else if (option === 'resume') {
          url_ = 'book/resume' // 恢复
          message = '恢复成功'
        } else if (option === 'delete') {
          url_ = 'book/delete' // 恢复
          message = '删除成功'
        }
        this.$post(url_, {id: id_.join(',')}).then((response) => {
          console.log(response)
          if (response.code === 0) {
            this.InitFn()
            _self.$message({
              message: message,
              type: 'success'
            })
            _self.InitFn()
          } else {
            console.log('请求失败')
          }
        }).catch((err) => {
          console.log(err)
        })
        // console.log(this.$refs.multipleTable.toggleRowSelection())
      },
      // 删除
      handleDetel (index, row) {
        console.log('编辑数据index', index)
        console.log('编辑数据row', row)
        this.bookName = row.name
        this.bookEtelId = row.id
        this.dialogVisible = true
      },
      // 禁止恢复借阅
      openBorrwBook (index, row) {
        console.log('序列号index', index)
        console.log('数据row', row)
        //  book/forbid 禁用
        // status 0可以恢复 1可以禁用
        // book/forbid/id/ 禁用
        // book/resume/id/ 恢复
        let url_ = 'book/resume' // 恢复
        let message = '恢复成功'
        let _self = this
        let status = 1
        if (row.status === 1) {
          url_ = 'book/forbid' // 禁用
          message = '禁用成功'
          status = 0
        }
        this.$post(url_, {id: row.id}).then((response) => {
          console.log(response)
          if (response.code === 0) {
            this.InitFn()
            _self.$message({
              message: message,
              type: 'success'
            })
            _self.arryList[index].status = status
          } else {
            console.log('请求失败')
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 确认删除图书
      DetelBook () {
        let _self = this
        this.$post('book/delete', {id: this.bookEtelId}).then((response) => {
          console.log(response)
          if (response.code === 0) {
            this.InitFn()
            _self.$message({
              message: '删除成功',
              type: 'success'
            })
            _self.dialogVisible = false
          } else {
            console.log('请求失败')
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 添加图书
      addBook () {
        this.editForm = {
          barcode: '',
          editor: '',
          name: '',
          position: '',
          press: '',
          status: '1',
          num: ''
        } // 编辑界面数据
        this.editFormVisible = true
        this.tieleName = '添加'
      },
      // 编辑
      handleEdit (index, row) {
        console.log('编辑数据index', index)
        console.log('编辑数据row', row)
        this.tieleName = '编辑'
        row.status = row.status.toString()
        for (let i in this.editForm) {
          this.editForm[i] = row[i]
        }
        this.editForm.id = row.id
        this.editFormVisible = true
      },
      // 选择用户人员
      userInfoFn () {
        this.dialogTableVisible = true
      },
      // 提交数据
      editSubmit () {
        // 验证信息
        let _self = this
        this.$refs['editForm'].validate((valid) => {
          if (valid) {
            console.log('提交信息')
            _self.submitBook()
            console.log('提交数据data', _self.editForm)
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 提交新增，编辑书籍
      submitBook () {
        // 判断新增 编辑
        let _self = this
        let url_ = 'device/add'
        let message = '添加成功'
        // 判断 tieleName添加，编辑
        // book/edit/id/707
        if (this.tieleName === '编辑') {
          url_ = 'device/edit/id/' + this.editForm.id
          message = '编辑成功'
        }
        this.$post(url_, this.editForm).then((response) => {
          console.log(response)
          if (response.code === 0) {
            if (_self.page === 1) {
              _self.InitFn()
            }
            if (this.tieleName === '编辑') {
              _self.InitFn()
            }
            _self.$message({
              message: message,
              type: 'success'
            })
            _self.editFormVisible = false
            _self.$refs['editForm'].resetFields()
          } else {
            console.log('请求失败')
          }
        }).catch((err) => {
          console.log(err)
        })
      },
      // 重置验证
      resetForm () {
        console.log('取消')
        this.editFormVisible = false
        this.$refs['editForm'].resetFields()
      },
      handleClose (done) {
        done()
        this.$refs['editForm'].resetFields()
      },
      // 点击全选
      selectAll (val) {
        // 全选所有跟空值，即使页面已经选择2项
        console.log('点击全选', val)
        console.log(val) // 所有选中值
        let applyBookBox = this.applyBookBox
        if (val.length !== 0) {
          // this.handleSelection = val
          for (let i = 0; i < val.length; i++) {
            if (!applyBookBox[val[i].id]) {
              // 不存在图书
              applyBookBox[val[i].id] = val[i]
            }
          }
        } else {
          // 清除所有 arryList
          for (let i = 0; i < this.arryList.length; i++) {
            if (this.applyBookBox[this.arryList[i].id]) {
              // 存在图书删除
              delete applyBookBox[this.arryList[i].id]
            }
          }
        }
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      },
      // 设置默认选中
      checked () {
        console.log('默认选项判断', this.applyBookBox)
        for (let i = 0; i < this.arryList.length; i++) {
          if (this.applyBookBox[this.arryList[i].id]) {
            console.log('数值', i)
            this.$refs.table.toggleRowSelection(this.arryList[i], true)
          }
        }
      },
      // 点击单选
      selectFnBox (val) {
        // 选择的是当前所有的选中，还需要比对未选中项 applyBookBoxInit
        console.log('本页面的列表数据', this.applyBookBoxInit)
        console.log('点击单选', val)
        let applyBookBox = this.applyBookBox
        if (val.length !== 0) {
          // 有选项 对本页面的选项进行比对
          let valBox = {}
          for (let i = 0; i < val.length; i++) {
            valBox[val[i].id] = val[i]
          }
          for (let i in this.applyBookBoxInit) {
            if (valBox[i]) {
              // 存在图书删除
              applyBookBox[i] = this.applyBookBoxInit[i]
            } else {
              delete applyBookBox[i]
            }
          }
        } else {
          // 清除所有 arryList
          for (let i in this.applyBookBoxInit) {
            delete applyBookBox[i]
          }
        }
        this.applyBookBox = Object.assign({}, this.applyBookBox, applyBookBox) // 更新视图对象
      },
      userlist (val) {
        console.log(this.applyBookBox)
        let userlList = ''
        let userlListId = ''
        // infoForm.a_user
        console.log(this.applyBookBox)
        for (let i in this.applyBookBox) {
          let className = this.applyBookBox[i].class_id
          if (this.applyBookBox[i].class_id === '') {
            className = '数据未添加'
          }
          userlList += (className + ',')
          userlListId += (this.applyBookBox[i].id + ',')
        }
        this.editForm.position = userlList.substring(0, userlList.length - 1)
        // this.editForm.position = userlListId.substring(0, userlListId.length - 1)
        this.dialogTableVisible = false
      },
      // 刷新页面
      refreshFn () {
        this.InitFn()
      }
    },
    mounted () {
    }
  }
</script>

<style lang="scss">
  #tablebox {
    display: flex;
    flex-direction: column;
  }
  .el-table{
    color:#000;
  }
  .right-box .container .main .content-container .input-val-box .input-top{
    width: 250px;
  }
</style>
